# encoding: utf-8
# @File  : main.py
# @Author: shaoyun
# @Date  :  2025/05/11
import uvicorn
from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware
from loguru import logger
from prometheus_client import generate_latest
from starlette.responses import RedirectResponse
from starlette.responses import Response

from app.api import api_router
from app.core.config import settings
from app.core.lifecycle import lifespan
from app.db.mysql import Base, engine
from app.services.monitor import Monitor

# 创建数据库表
Base.metadata.create_all(bind=engine)

# 配置日志（loguru）
logger.add(
    settings.LOG_FILE_PATH,
    rotation="1 day",
    retention="7 days",
    level=settings.LOG_LEVEL,
    format="{time:YYYY-MM-DD HH:mm:ss} | {level} | {message}",
)

# 创建FastAPI应用
app = FastAPI(
    title=settings.PROJECT_NAME,
    version=settings.VERSION,
    openapi_url=f"{settings.API_V1_STR}/openapi.json",
    docs_url=f"{settings.API_V1_STR}/docs",
    redoc_url=f"{settings.API_V1_STR}/redoc",
    description="""
    分布式爬虫管理系统 API
    基于FastAPI和AI优化的分布式爬虫管理平台，支持：
    - 多节点任务调度
    - AI智能优化
    - Docker容器化部署
    - 实时性能监控
    - 定时任务管理
    """,
    lifespan=lifespan
)

# 配置CORS
app.add_middleware(
    CORSMiddleware,
    allow_origins=settings.ALLOWED_HOSTS,
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)

# 注册API路由
app.include_router(api_router, prefix=settings.API_V1_STR)


@app.get("/", include_in_schema=False)
async def redirect_to_docs():
    """重定向到API文档"""
    return RedirectResponse(url=f"{settings.API_V1_STR}/docs")


@app.get("/health", tags=["System"])
async def health_check():
    """健康检查接口"""
    return {
        "status": "healthy",
        "version": settings.VERSION,
        "project": settings.PROJECT_NAME
    }

@app.get("/metrics", tags=["System"], include_in_schema=False)
async def get_metrics():
    """Prometheus metrics endpoint"""
    # 使用 Monitor 类的 registry 来生成指标
    return Response(
        generate_latest(Monitor.registry),
        media_type="text/plain; version=0.0.4; charset=utf-8"
    )


if __name__ == "__main__":
    logger.info(f"Starting {settings.PROJECT_NAME} API server...")
    logger.info(f"API docs available at: http://localhost:8000{settings.API_V1_STR}/docs")

    uvicorn.run(
        app,
        host="0.0.0.0",
        port=8000,
        log_config={
            "version": 1,
            "disable_existing_loggers": False,
            "formatters": {
                "default": {
                    "format": "%(asctime)s - %(name)s - %(levelname)s - %(message)s",
                },
            },
            "handlers": {
                "default": {
                    "formatter": "default",
                    "class": "logging.StreamHandler",
                    "stream": "ext://sys.stdout",
                },
            },
            "root": {
                "level": settings.LOG_LEVEL,
                "handlers": ["default"],
            },
        }
    )